<?php namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Services\wxh5pay\config\wxh5pay;
use App\Http\Services\wxh5pay\OrderH5;
use App\Plan;
use App\PlanJoin;
use App\User;
use App\UserInfo;
use EasyWeChat\Payment\Order;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use Log;

class PaymentController extends Controller
{
    /**
     * 微信内支付
     */
    public function payByWechatJsApi(Guard $guard,Request $request){
        $orderNum = $request->get('order_num');

        if($guard->guest())
            return response()->json(['level'=>'error','message'=>'请先登录']);

        /** @var User $user */
        $user = $guard->user();

        /** @var PlanJoin $planJoin */
        $planJoin = PlanJoin::whereOrderNum($orderNum)->first();
        if(!$planJoin)
            return response()->json(['level'=>'error','message'=>'当前订单不存在']);

        $title = '';
        /** @var Plan $thatPlan */
        $thatPlan = Plan::whereId($planJoin->plan_id)->first();
        if($thatPlan){
            $title = $thatPlan->title;
        }

        $openId = $user->wechat_openid;
        $app = app("wechat");
        $attributes = [
            'trade_type'       => 'JSAPI',
            'body'             => '会员费用',
            'detail'           => $title.'会员费用',
            'out_trade_no'     => $orderNum,
            'total_fee'        => (float)$planJoin->amount * 100,
            'notify_url'       => route('Api.Payment.wechatPayCallBack'),
            'openid'           => $openId,
        ];
        $payment = $app->payment;
        $order = new Order($attributes);
        $result = $payment->prepare($order);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            $prepayId = $result->prepay_id;
            $json = $payment->configForPayment($prepayId);
            return response()->json(['level'=>'success','message'=>trans('获取支付信息成功'),'data'=>json_decode($json)]);
        }else{
            return response()->json(['level'=>'error','message'=>'创建支付信息失败','data'=>$result]);
        }
    }

    /**
     * 微信H5支付
     */
    public function payByWechatH5(Guard $guard,Request $request){
        $orderNum = $request->get('order_num');

        if($guard->guest())
            return response()->json(['level'=>'error','message'=>'请先登录']);

        /** @var User $user */
        $user = $guard->user();

        /** @var PlanJoin $planJoin */
        $planJoin = PlanJoin::whereOrderNum($orderNum)->first();
        if(!$planJoin)
            return response()->json(['level'=>'error','message'=>'当前订单不存在']);

        $title = '';
        /** @var Plan $thatPlan */
        $thatPlan = Plan::whereId($planJoin->plan_id)->first();
        if($thatPlan){
            $title = $thatPlan->title;
        }

        $config = wxh5pay::getConfig();
        $order = new OrderH5($config);
        $order->setParams([
            'body'             => '会员费用',
            'detail'           => $title.'会员费用',
            'out_trade_no'     => $orderNum,
            'total_fee'        => (float)$planJoin->amount * 100,
            'trade_type'       => 'MWEB',
            'device_info'      => $config['device_info'],
            'spbill_create_ip' => $request->ip(),
            'notify_url'       => route('Api.Payment.wechatPayCallBack'),
            'scene_info'       => '{"h5_info": {"type":"Wap","wap_url": "http://wtb100.com","wap_name": "乌托邦会员支付"}}'
        ]);
        $res = $order->unifiedorder();
        if(!$res){
            return response()->json(['level'=>'error','message'=>'创建支付信息失败','data'=>$res]);
        }else {
            return response()->json(['level'=>'success','message'=>trans('获取支付信息成功'),'data'=>$res]);
        }
    }

    public function wechatPayCallBack(){
        $app = app("wechat");

        $response = $app->payment->handleNotify(function($notify, $successful){
            Log::info('order_num=>'.$notify->out_trade_no);

            /** @var PlanJoin $thatPlanJoin */
            $thatPlanJoin= PlanJoin::whereOrderNum($notify->out_trade_no)->first();
            if (!$thatPlanJoin) {
                return 'Order not exist.';
            }

            if ($thatPlanJoin->is_pay == 1) {
                return true;
            }

            if ($successful) {
                $thatPlanJoin->pay_time = date('Y-m-d H:i:s',time());
                $thatPlanJoin->is_pay   = 1;
                $thatPlanJoin->pay_type = 'wxpay';
//                $thatPlanJoin->status   = 1;
                $thatPlanJoin->save();

                $thatUserInfo = UserInfo::whereUserId($thatPlanJoin->user_id)->first();
                if($thatUserInfo){
                    if($thatUserInfo->is_member == 0) {
                        $thatUserInfo->is_member = 1;
                        $thatUserInfo->save();
                    }
                }

                return true;
            } else {
                $thatPlanJoin->is_pay = 0;
                $thatPlanJoin->save();

                return 'fail.';
            }



        });

        return $response;
    }
}